<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


//  api日志
class Api_log 
{
    // 等级 0 DEBUG 1 INFO 2 WARN 3 ERROR 
    private $_logLevel = 0;
    private $_dirname = 'appApi';
    private $_logName = array('DEBUG', 'INFO', 'WARN', 'ERROR');
    function __construct()
    {
        $this->CI = &get_instance();
        $this->CI->load->library('Myexception');
        set_exception_handler(array("Myexception","exceptionHandler"));
        set_error_handler(array("Myexception","errorHandler"));
        //设置一个程序异常终止的时候的错误处理函数
        register_shutdown_function(array("Myexception","shutdownHandler"));
    }

    /**
     * 添加一组日志信息到日志对象中
     *
     *     $log->add(Log::ERROR, 'Could not locate user: :user', array(
     *         ':user' => $username,
     *     ));
     *
     * @param   string  这组日志对象的错误等级
     * @param   string  日志消息
     * @param   array   记录错误位置信息
     * 
     *  $this->api_log->add('INFO','jjjjyrtj',array('file'=>__FILE__,'line'=>__LINE__));
     *
     * @return  Log
     * 
     */
    public function add($level, $message, array $additional=null) {
        // Create a new message and timestamp it
        $message = array (
                'time'  => date('Y-m-d H:i:s', time()),
                'level' => $level,
                'body'  => $message,
                'file'  => isset($additional['file']) ? $additional['file'] : NULL,
                'line'  => isset($additional['line']) ? $additional['line'] : NULL,
        );

        $filename = $this->createDir();
        $ip = $this->CI->input->ip_address();
        file_put_contents($filename, PHP_EOL.$message['time'].' --- '.$ip.' --- '.$message['level'].': '.$message['body'].'     [at file]:'.$message['file'].'      [at line]:'.$message['line'], FILE_APPEND);

        return $this;
    }

    private function createDir()
    {
        $dirname = $this->_dirname;
        $fileExt = '.txt';
        $directory = APPPATH.'logs';
        // “logs”这一级目录
        if ( ! is_dir($directory)) {
            // 如果“年”级目录不存在，创建
            mkdir($directory, 0777);
            // 设置目录权限(must be manually set to fix umask issues)
            chmod($directory, 0777);
        }

        $directory .= DIRECTORY_SEPARATOR.$dirname;
        // “logs”这一级目录
        if ( ! is_dir($directory)) {
            // 如果“年”级目录不存在，创建
            mkdir($directory, 0777);
            // 设置目录权限(must be manually set to fix umask issues)
            chmod($directory, 0777);
        }

        // “年”这一级目录
        $directory .= DIRECTORY_SEPARATOR.date('Y');
        if ( ! is_dir($directory)) {
            // 如果“年”级目录不存在，创建
            mkdir($directory, 0777);
            // 设置目录权限(must be manually set to fix umask issues)
            chmod($directory, 0777);
        }

        // “月”这一级目录
        $directory .= DIRECTORY_SEPARATOR.date('m');
        if ( ! is_dir($directory)) {
            // 如果“月”级目录不存在，创建
            mkdir($directory, 0777);
            // 设置权限 (must be manually set to fix umask issues)
            chmod($directory, 0777);
        }

        // 要写入的文件
        $filename = $directory.DIRECTORY_SEPARATOR.date('Y-m-d').$fileExt;
        if ( ! file_exists($filename)) {
            $initFont = ' 日志消息';
            // 如果不存在日志文件，创建，并在记录日志开始写入安全验证程序
            file_put_contents($filename, date('Y-m-d').$initFont.PHP_EOL);
            // 设置文件权限为所有用户可读可写
            chmod($filename, 0777);
        }

        return $filename;
    }

    public function setDir($dirname = '')
    {
        $dirname = !empty($dirname) ? $dirname : 'appApi';
        $this->_dirname = $dirname;
    }
    
}

